package algorithm;

import dataset.Dataset;
import exception.KNoMeaningException;
import scicalc.Calculate;

import java.util.*;

public class KMeans extends AbstractClusterAlgorithm {
    private int k = 2;
    private double[][] mu;

    @Override
    public long fit(Dataset X) {
        long start = System.currentTimeMillis();
        int[] r = Calculate.randomIntArray(0, X.shape[0], this.k);
        this.mu = Calculate.choose(X.dataset, r);
        while (true) {
            Map<Integer, List<Integer>> clusters = new HashMap<>();
            for (int i = 0; i < this.k; i++) {
                clusters.put(i, new ArrayList<>());
            }
            for (int i = 0; i < X.shape[0]; i++) {
                double[] distance = Calculate.sqrt(Calculate.sum(Calculate.pow(Calculate.minus(X.dataset[i], this.mu), 2), Calculate.AXIS_1));
                int lambda = Calculate.argmin(distance);
                clusters.get(lambda).add(i);
            }
            double[][] mu_ = new double[this.mu.length][this.mu[0].length];
            for (int i = 0; i < k; i++) {
                double[][] choose = Calculate.choose(X.dataset, clusters.get(i));
                mu_[i] = Calculate.mean(choose, Calculate.AXIS_0);
            }
            if (Calculate.sum(Calculate.pow(Calculate.minus(mu_, this.mu), 2)) < 1e-8) {
                this.labels = new int[X.shape[0]];
                for (int i = 0; i < k; i++) {
                    List<Integer> list = clusters.get(i);
                    for (Integer number : list)
                        this.labels[number] = i;
                }
                break;
            } else {
                this.mu = mu_;
            }
        }
        this.result.shape[0] = X.shape[0];
        this.result.shape[1] = X.shape[1];
        this.result.dataset = X.dataset;
        this.result.label = this.labels;
        return System.currentTimeMillis() - start;
    }

    public void setK(int k) {
        if (k < 2) {
            try {
                throw new KNoMeaningException(k);
            } catch (KNoMeaningException e) {
                e.printStackTrace();
            }
        } else this.k = k;
    }
}
